<script lang="ts" setup>
import BaseButton from "@/components/BaseButton/index.vue";
import BaseUpDown from "@/components/BaseUpDown/index.vue";
import useSearch from "@/hooks/useSearch";
import useData from "./hooks/useData";
import { useUserStore } from "@/stores/modules/user";
import DateRange from "@/components/DateRange/index.vue";
import { PORT1 } from "@/api/config/servicePort";

const { pageData, roleMap } = useData();
import { getDataByPage } from "@/api/modules/attack-traceability/session-log";
import UpdateForm from "./components/UpdateForm/index.vue";
import UpdateFormPassword from "./components/UpdateFormPassword/index.vue";

const userStore = useUserStore();
const username = computed(() => userStore.userInfo.name);
const { tableData, loadData, formData, reloadData } = useSearch({
  defaultData: {
    ipproto: "0"
  },
  responseKey: {
    list: "result.data",
    total: "result.total"
  }
});

function loadDataCb() {
  loadData({
    api: getDataByPage,
    sendData: {
      curpage: formData.pageNum - 1,
      perpage: formData.pageSize,
      sip: formData.sip || "0",
      from: formData.from || "0",
      mac: formData.mac || "0",
      start_time: parseInt(new Date(formData.start_time).getTime() / 1000) || "0",
      end_time: parseInt(new Date(formData.end_time).getTime() / 1000) || "0",
      dip: formData.dip || "",
      ipproto: formData.ipproto || "0",
      sport: formData.sport || "",
      dport: formData.dport || ""
    }
  });
}

loadDataCb();

function reloadDataCb() {
  reloadData();

  loadData({
    api: getDataByPage,
    sendData: {
      pageNum: formData.pageNum - 1,
      pageSize: formData.pageSize
    }
  });
}

loadDataCb();

/**删除*/
import useDelete from "@/hooks/useDelete";
import { computed, nextTick } from "vue";
import BaseCollapse from "@/components/BaseCollapse/index.vue";

function download(url) {
  return new Promise((resolve, reject) => {
    const iframe = document.createElement("iframe");
    iframe.style.display = "none";

    function iframeLoad() {
      console.log("iframe onload");
      const win = iframe.contentWindow;
      const doc = win.document;
      if (win.location.href === url) {
        if (doc.body.childNodes.length > 0) {
          // response is error
        }
        iframe.parentNode.removeChild(iframe);
      }
    }

    if ("onload" in iframe) {
      iframe.onload = iframeLoad;
    } else if (iframe.attachEvent) {
      iframe.attachEvent("onload", iframeLoad);
    } else {
      iframe.onreadystatechange = function onreadystatechange() {
        if (iframe.readyState === "complete") {
          iframeLoad;
        }
      };
    }
    iframe.src = "";
    document.body.appendChild(iframe);

    setTimeout(function loadUrl() {
      iframe.contentWindow.location.href = url;
      resolve();
    }, 150);
  });
}

async function exportExcel() {
  let start = 0;
  let ends = 0;

  if (formData.start_time == "") {
    start = 0;
  } else {
    start = new Date(formData.start_time).getTime() / 1000;
  }
  if (formData.end_time == "") {
    ends = 0;
  } else {
    ends = new Date(formData.end_time).getTime() / 1000;
  }
  const pageSize = 100000;
  const count = Math.ceil(tableData.total / pageSize);
  let arr = new Array(count).fill(0).map((item, index) => index);
  for await (let i of arr) {
    await download(
      PORT1 +
        "/monitor/flow/flow_export?sip=" +
        formData.sip +
        "&mac=" +
        formData.mac +
        "&start_time=" +
        start +
        "&end_time=" +
        ends +
        "&start_count=" +
        i * pageSize
    );
  }
  console.log(count);
}
</script>

<template>
  <BaseUpDown>
    <template #up>
      <BaseCollapse title="">
        <el-form label-position="right">
          <div class="h-box">
            <el-form-item label-width="72px" label="源MAC">
              <el-input placeholder="请输入" style="width: 140px" v-model="formData.mac"></el-input>
            </el-form-item>
            <el-form-item class="mg-l-lg" label-width="72px" label="源IP">
              <el-input placeholder="请输入" style="width: 140px" v-model="formData.sip"></el-input>
            </el-form-item>
            <el-form-item class="mg-l-lg" label-width="72px" label="源端口">
              <el-input placeholder="请输入" style="width: 100px" v-model="formData.sport"></el-input>
            </el-form-item>
            <el-form-item class="mg-l-lg" label-width="72px" label="协议">
              <el-select v-model="formData.ipproto" style="width: 100px">
                <el-option value="0" label="全部" />
                <el-option value="1" label="ICMP" />
                <el-option value="6" label="TCP" />
                <el-option value="17" label="UDP" />
              </el-select>
            </el-form-item>
          </div>
          <div class="h-box">
            <el-form-item label-width="72px" label="目的IP">
              <el-input placeholder="请输入" style="width: 140px" v-model="formData.dip"></el-input>
            </el-form-item>
            <el-form-item class="mg-l-lg" label-width="72px" label="目的端口">
              <el-input placeholder="请输入" style="width: 100px" v-model="formData.dport"></el-input>
            </el-form-item>
            <el-form-item class="mg-l-lg" label-width="72px" label="时间">
              <DateRange v-model:start="formData.start_time" v-model:end="formData.end_time" />
              <base-button @click="loadDataCb" class="mg-l-sm" type="search_icon_text"></base-button>
              <base-button @click="reloadDataCb" type="reset_icon_text"></base-button>
              <base-button @click="exportExcel" type="export_icon_text"></base-button>
            </el-form-item>
          </div>
        </el-form>
      </BaseCollapse>
    </template>
    <he-table
      @handle-current-change="loadDataCb"
      :total="tableData.total"
      v-model:page-size="formData.pageSize"
      v-model:page-num="formData.pageNum"
      operate-width="180px"
      :operate-list="[]"
      :table-data="tableData.list"
      :column-data="pageData.columnData"
      :show-multiple="false"
      :show-summary="false"
      :show-operate="false"
      :show-multiple-column="false"
      :show-pagination="true"
      @select="selectCb"
    >
      <template #7Default="{ data }"> {{ data.row[9] }} / {{ data.row[10] }} </template>
      <template #operationDefault="{ data }">
        <UpdateForm
          :row-data="{
            id: data.row[data.row.length - 1],
            name: data.row[1],
            role: roleMap.get(data.row[2])
          }"
          :title="`编辑用户:${data.row[1]}`"
          @success="loadDataCb"
        >
          <base-button type="edit_text"></base-button>
        </UpdateForm>
        <UpdateFormPassword
          :row-data="{
            id: data.row[data.row.length - 1],
            name: data.row[1],
            role: roleMap.get(data.row[2])
          }"
          :title="`重置密码:${data.row[1]}`"
          @success="loadDataCb"
        >
          <el-button type="primary" link>重置密码</el-button>
        </UpdateFormPassword>
        <base-button
          v-if="username != data.row[1]"
          @click="deleteCb(data.row[data.row.length - 1])"
          type="del_text"
        ></base-button>
      </template>
    </he-table>
  </BaseUpDown>
</template>
